package com.healthdata.controller;

import com.healthdata.common.ApiResponse;
import com.healthdata.service.DataCleanService;
import com.healthdata.service.ExportService;
import com.healthdata.service.FileParseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/data-clean")
public class DataCleanController {

    @Autowired
    private FileParseService fileParseService;

    @Autowired
    private DataCleanService dataCleanService;

    @Autowired
    private ExportService exportService;

    @PostMapping("/clean")
    public ApiResponse<List<Map<String, Object>>> cleanData(
            @RequestParam("file") MultipartFile file,
            @RequestParam("format") String format,
            @RequestParam(value = "targetColumn", required = false) String targetColumn,
            @RequestParam(value = "dependentColumns", required = false) List<String> dependentColumns) {

        // 参数校验：确保targetColumn存在
        if (targetColumn == null || targetColumn.trim().isEmpty()) {
            return ApiResponse.error(400, "targetColumn参数不能为空");
        }

        if (!Arrays.asList("csv", "excel", "json").contains(format.toLowerCase())) {
            // 直接返回 ApiResponse 对象
            return ApiResponse.error(400, "Unsupported file format: " + format);
        }

        try {
            // 解析文件
            List<Map<String, Object>> data = fileParseService.parseFile(file, format);

            // 确保数据不为空
            if (data == null || data.isEmpty()) {
                return ApiResponse.error(400, "解析后的文件数据为空");
            }

            // 执行数据清洗
            List<Map<String, Object>> cleanedData = dataCleanService.cleanMissingValues(
                    data, targetColumn, dependentColumns);

            // 返回结果
            return ApiResponse.success(cleanedData);
        } catch (Exception e) {
            return ApiResponse.error(500, e.getMessage());
        }
    }

    // DataCleanController.java 修改部分
    @PostMapping("/remove-duplicates")
    public ApiResponse<List<Map<String, Object>>> removeDuplicates(
            @RequestParam("file") MultipartFile file,
            @RequestParam("format") String format,
            @RequestParam("primaryKeyColumns") List<String> primaryKeyColumns,
            @RequestParam("duplicateCheckColumns") List<String> duplicateCheckColumns) { // 添加缺失参数

        if (!Arrays.asList("csv", "excel", "json").contains(format.toLowerCase())) {
            return ApiResponse.error(400, "Unsupported file format: " + format);
        }

        try {
            List<Map<String, Object>> data = fileParseService.parseFile(file, format);
            // 传递三个参数：数据、主键列、查重列
            List<Map<String, Object>> cleanedData = dataCleanService.removeDuplicates(
                    data, primaryKeyColumns, duplicateCheckColumns);

            return ApiResponse.success(cleanedData);
        } catch (Exception e) {
            return ApiResponse.error(500, e.getMessage());
        }
    }

//    @PostMapping("/clean/export-excel")
//    public ResponseEntity<byte[]> exportCleanedDataToExcel(
//            @RequestParam("file") MultipartFile file,
//            @RequestParam("format") String format,
//            @RequestParam(value = "targetColumn", required = false) String targetColumn,
//            @RequestParam(value = "dependentColumns", required = false) List<String> dependentColumns,
//            @RequestParam(required = false) String filename) {
//
//        try {
//            // 解析文件
//            List<Map<String, Object>> data = fileParseService.parseFile(file, format);
//
//            // 确保数据不为空
//            if (data == null || data.isEmpty()) {
//                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
//            }
//
//            // 执行数据清洗
//            List<Map<String, Object>> cleanedData = dataCleanService.cleanMissingValues(
//                    data, targetColumn, dependentColumns);
//
//            // 在控制台输出JSON数据
//            System.out.println(cleanedData.toString());
//
//            // 将数据转换为DataRow列表
//            List<com.healthdata.entity.DataRow> dataRows = convertToDataRows(cleanedData);
//
//            // 确保文件名包含正确的扩展名
//            filename = filename != null ? filename : "cleaned_health_data";
//            if (!filename.toLowerCase().endsWith(".xlsx")) {
//                filename += ".xlsx";
//            }
//
//            // 调用导出服务导出为Excel
//            byte[] content = exportService.exportToExcel(dataRows);
//
//            HttpHeaders headers = new HttpHeaders();
//            headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
//            headers.setContentDispositionFormData("attachment", filename);
//            headers.setContentLength(content.length);
//
//            return new ResponseEntity<>(content, headers, HttpStatus.OK);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
//        }
//    }


    // 新增方法，用于去重并导出
    @PostMapping("/remove-duplicates/export")
    public ResponseEntity<byte[]> removeDuplicatesExport(
            @RequestParam("file") MultipartFile file,
            @RequestParam("format") String format,
            @RequestParam("primaryKeyColumns") List<String> primaryKeyColumns,
            @RequestParam("duplicateCheckColumns") List<String> duplicateCheckColumns,
            @RequestParam("exportFormat") String exportFormat,
            @RequestParam(required = false) String filename) {

        try {
            // 解析文件
            List<Map<String, Object>> data = fileParseService.parseFile(file, format);

            // 确保数据不为空
            if (data == null || data.isEmpty()) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
            }

            // 执行去重操作
            List<Map<String, Object>> deduplicatedData = dataCleanService.removeDuplicates(
                    data, primaryKeyColumns, duplicateCheckColumns);

            // 在控制台输出JSON数据
            System.out.println(deduplicatedData.toString());

            // 将数据转换为DataRow列表
            List<com.healthdata.entity.DataRow> dataRows = convertToDataRows(deduplicatedData);

            // 确保文件名包含正确的扩展名
            filename = filename != null ? filename : "deduplicated_health_data";
            filename = addExtensionIfMissing(filename, exportFormat);

            // 调用导出服务导出数据
            return exportService.exportData(exportFormat, dataRows, filename);

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    private List<com.healthdata.entity.DataRow> convertToDataRows(List<Map<String, Object>> data) {
        List<com.healthdata.entity.DataRow> dataRows = new java.util.ArrayList<>();
        for (Map<String, Object> row : data) {
            com.healthdata.entity.DataRow dataRow = new com.healthdata.entity.DataRow();
            dataRow.setValues(row);
            dataRows.add(dataRow);
        }
        return dataRows;
    }


    // 新增方法，用于清洗数据并导出
    @PostMapping("/clean/export")
    public ResponseEntity<byte[]> cleanDataExport(
            @RequestParam("file") MultipartFile file,
            @RequestParam("format") String format,
            @RequestParam(value = "targetColumn", required = false) String targetColumn,
            @RequestParam(value = "dependentColumns", required = false) List<String> dependentColumns,
            @RequestParam("exportFormat") String exportFormat,
            @RequestParam(required = false) String filename) {

        try {
            // 解析文件
            List<Map<String, Object>> data = fileParseService.parseFile(file, format);

            // 确保数据不为空
            if (data == null || data.isEmpty()) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
            }

            // 执行数据清洗
            List<Map<String, Object>> cleanedData = dataCleanService.cleanMissingValues(
                    data, targetColumn, dependentColumns);

            // 在控制台输出JSON数据
            System.out.println(cleanedData.toString());

            // 将数据转换为DataRow列表
            List<com.healthdata.entity.DataRow> dataRows = convertToDataRows(cleanedData);

            // 确保文件名包含正确的扩展名
            filename = filename != null ? filename : "cleaned_health_data";
            filename = addExtensionIfMissing(filename, exportFormat);

            // 调用导出服务导出数据
            return exportService.exportData(exportFormat, dataRows, filename);

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

//    private List<com.healthdata.entity.DataRow> convertToDataRows(List<Map<String, Object>> data) {
//        List<com.healthdata.entity.DataRow> dataRows = new java.util.ArrayList<>();
//        for (Map<String, Object> row : data) {
//            com.healthdata.entity.DataRow dataRow = new com.healthdata.entity.DataRow();
//            dataRow.setValues(row);
//            dataRows.add(dataRow);
//        }
//        return dataRows;
//    }

    // 根据格式添加正确的文件扩展名
    private String addExtensionIfMissing(String filename, String format) {
        if (format.equalsIgnoreCase("excel") || format.equalsIgnoreCase("xlsx")) {
            if (!filename.toLowerCase().endsWith(".xlsx")) {
                filename += ".xlsx";
            }
        } else if (format.equalsIgnoreCase("csv")) {
            if (!filename.toLowerCase().endsWith(".csv")) {
                filename += ".csv";
            }
        }
        return filename;
    }
}